#!/bin/bash

######################################################################
#
#  Copyright (c) 2015 arakasi72 (https://github.com/arakasi72)
#
#  --> Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
######################################################################

PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/bin:/sbin

lineno=$(sed -n '/dload-loc/=' /etc/nginx/sites-available/default)
dlstatus=disabled

# function to ask user for y/n response
ask_user(){
while true
  do
    read answer
    case $answer in [Yy]* ) return 0 ;;
                    [Nn]* ) return 1 ;;
                        * ) echo "Enter y or n";;
    esac
  done
}

if [ "$(id -u)" != "0" ]; then
  echo "Must be run as root, directly or with sudo"
  exit 1
fi

if [ -f /etc/nginx/conf.d/rtdload ]; then rm -f /etc/nginx/conf.d/rtdload; fi
sed -i '/rtdload/d' /etc/nginx/sites-available/default

if [ $# = 0 ]; then
  rtdgrep1=$(grep dload-loc /etc/nginx/sites-available/default)
  rtdgrep2=$(grep dload-loc /etc/nginx/sites-available/default | grep '#')

  if [ -n "$rtdgrep1" -a -z "$rtdgrep2" ]; then dlstatus=enabled; fi

  if [ -t 1 ]; then
    if [ $dlstatus = enabled ]; then
      echo "Http downloads are Enabled"
      dlswitch=disable
    elif [ $dlstatus = disabled ]; then
      echo "Http downloads are Disabled"
      dlswitch=enable
    fi

    echo "Would you like to $dlswitch http downloads (y/n)?"
    if ask_user; then
      rtdload $dlswitch
    fi
  else
    echo $dlstatus
  fi

elif [ "$1" = "enable" ]; then
  if ! [ -f /etc/nginx/sites-available/dload-loc ]; then
    cp -f /etc/rtinst/conf/nginxsitedl /etc/nginx/sites-available/dload-loc
  fi

  if [ -z "$lineno" ]; then
    sed -i '/location \~ \/\\\.ht/ i\        include \/etc\/nginx\/sites-available\/dload-loc;\n' /etc/nginx/sites-available/default
  else
    sed -i '/dload-loc/ c\        include \/etc\/nginx\/sites-available\/dload-loc;' /etc/nginx/sites-available/default
  fi
  service nginx reload
  echo "http download enabled"

elif [ "$1" = "disable" ]; then
  if ! [ -z "$lineno" ]; then
    sed -i '/dload-loc/ c\        #include \/etc\/nginx\/sites-available\/dload-loc;' /etc/nginx/sites-available/default
    service nginx reload
  fi
  echo "http download disabled"
else
  echo "argument must be enable or disable"
  exit 1
fi
